<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/03/01
 * Time: 10:34
 * @link http://www.lmterp.cn
 */

namespace app\command;

use app\common\library\Tools;
use app\common\model\Orders;
use app\common\service\product\StockService;
use think\console\input\Option;
use think\facade\Log;

/**
 * 占用库存
 * Class LockStock
 * @package app\command
 */
class LockStock extends BaseCommand
{

    /**
     * 开始时间
     * @var string
     */
    protected $startDate;

    /**
     * 结束时间
     * @var string
     */
    protected $endDate;

    protected function configure()
    {
        $this->setName('lock_stock')
            ->addOption("action", null, Option::VALUE_REQUIRED, "占用库存方式，默认为订单")
            ->addOption("type", null, Option::VALUE_REQUIRED, "默认占用库存，可选: lock/unlock")
            ->addOption("start_date", null, Option::VALUE_REQUIRED, "开始导入时间，默认为今天")
            ->addOption("end_date", null, Option::VALUE_REQUIRED, "结束导入时间")
            ->addOption("warehouse_id", null, Option::VALUE_REQUIRED, "仓库id多个使用英文逗号分开")
            ->addOption("ids", null, Option::VALUE_REQUIRED, "订单id，多个使用英文逗号分开");
    }

    protected function handler()
    {
        $action = $this->input->hasOption('action')
                ? $this->input->getOption('action')
                : 'order';
        $type = $this->input->hasOption('type')
                ? $this->input->getOption('type')
                : 'lock';
        // 处理时间范围
        $this->startDate = $this->input->hasOption('start_date')
            ? $this->input->getOption('start_date')
            : date('Y-m-d');
        $this->endDate = $this->input->hasOption('end_date')
            ? $this->input->getOption('end_date')
            : date('Y-m-d', strtotime("1day"));

        $action .= ucfirst($type);
        if(!method_exists($this, $action)) return;

        // 处理库存
        $this->$action();
    }

    /**
     * 订单占用库存
     * @date 2021/03/01
     * @author longli
     */
    private function orderLock()
    {
        Log::info('订单开始占用库存');
        $succ = [];
        $hasIds = $this->input->hasOption('ids');
        $status = [Orders::ORDER_WAREHOUSE, Orders::ORDER_WAIT_PUR, Orders::ORDER_WAIT_PUR_ING, Orders::ORDER_LACK];
        if($hasIds) $status[] = Orders::ORDER_UNLOCK;
        $this->builderOrder($status)->chunk($this->defChunk, function($orders) use(&$succ)
        {
            foreach($orders as $order)
            {
                if(($msg = StockService::orderLockStock($order)) !== true)
                {
                    Log::info($msg);
                    continue;
                }
                $succ[$order->order_sn] = $order->order_id;
            }
        });
        if($hasIds)
        {
            $msg = "";
            if(!empty($succ))
            {
                $temp = explode(',', $this->input->getOption('ids'));
                $msg = Tools::equalsArray($temp, $succ)
                    ? "订单占用库存成功"
                    : "订单【" . join(', ', array_keys($succ)) . "】占用库存成功";
            }
            $this->output->write($msg);
        }
        Log::info('订单占用库存完成');
    }

    /**
     * 构建需要处理的订单
     * @param array $status 订单状态，默认为待处理
     * @return Orders 订单列表
     * @date 2021/03/02
     * @author longli
     */
    private function builderOrder($status = [])
    {
        if(empty($status)) $status = Orders::ORDER_WAIT;
        $orders = Orders::with(['detail'])
            ->whereIn("order_status", $status);
        if($this->input->hasOption('warehouse_id'))
            $orders->whereIn("warehouse_id", replaceStr($this->input->getOption('warehouse_id')));

        // 获取默认值
        if($this->input->hasOption('ids'))
        {
            $orders->whereIn("order_id", replaceStr($this->input->getOption('ids')));
        }
        else
        {
            $orders->where([
                ['create_time', 'egt', $this->startDate],
                ['create_time', 'elt', $this->endDate]
            ]);
        }
        return $orders;
    }

    /**
     * 订单释放库存
     * @date 2021/03/01
     * @author longli
     */
    private function orderUnlock()
    {
        Log::info('订单开始释放库存');
        $succ = [];
        $this->builderOrder([Orders::ORDER_LOCK])->chunk($this->defChunk, function($orders) use(&$succ)
        {
            foreach($orders as $order)
            {
                if(($msg = StockService::orderUnlockStock($order)) !== true)
                {
                    Log::info($msg);
                    continue;
                }
                $succ[$order->order_sn] = $order->order_id;
            }
        });
        if($this->input->hasOption('ids'))
        {
            $msg = "";
            if(!empty($succ))
            {
                $temp = explode(',', $this->input->getOption('ids'));
                $msg = Tools::equalsArray($temp, $succ)
                    ? "订单释放库存成功"
                    : "订单【" . join(', ', array_keys($succ)) . "】释放库存成功";
            }
            $this->output->write($msg);
        }
        Log::info('订单释放库存完成');
    }
}
